var defaultParams; //默认选中行
var tableData; //定义列表名称
// 删除
function deleteTr(listName, url) {
    if (defaultParams) {
        var ids = [defaultParams[listName + "Id"]]
        layer.confirm('确定删除选中？', {
             title:"温馨提示",
            btn: ['确定', '取消'] //按钮

        }, function() {
            defaultParams = ""
            $.ajax({
                type: "post",
                url: url,
                dataType: "json",
                contentType: 'application/json',
                data: JSON.stringify({ "ids": ids }),
                cache: false,
                success: function(data) {
                    if (data.message === "成功") {
                        layer.msg('删除成功', { time: 1000, icon: 1 });
                        $("#table").bootstrapTable('refresh');
                    } else {
                        layer.msg('删除失败', { time: 1000, icon: 1 });

                    }

                },
                error: function() {
                    layer.msg('请求出错');
                }
            })
        }, function() {
            layer.msg('删除操作取消', {
                time: 2000
            });
            defaultParams = ""
            $("#table").bootstrapTable('refresh');
        });
    } else {
        layer.msg('请选择删除项');
    }

}
//数据同步
function refreshData() {
    $.ajax({
        type: "POST",
        contentType: 'application/json',
        url: "/operation/system/user/sync",
        dataType: "json",
        cache: false,
        success: function(data) {
            if(data.message=="成功"){
                layer.msg("数据同步成功");
            }
        },
        error: function(e) {
            var errorMessage = JSON.parse(e.responseText).errors[0].message;
            layer.msg(errorMessage);
        }
    })
}
//返回
function back() {
    $("#buttonBack").hide()
    $("#buttonAdd").show()
    $("#buttonModify").show()
    $("#buttonDelete").show()
    $("#refreshData").show()
    $(".buttonSearchBox").show()
    $(".bootstrap-table").show()
    $(".contentInput").hide()
    $("#table").bootstrapTable('refresh');
    defaultParams = ""
    $("#submitButton").attr("disabled", false)
}
//修改
function modify(listName) {
    if (defaultParams) {
        // 获取详情
        $.ajax({
            url: "/operation/system/" + listName + "/" + defaultParams[listName + "Id"],
            type: "get",
            dataType: "json",
            cache: false,
            success: function(data) {
                if (data.message === "成功") {
                    $("#name").val(data.data[listName + "Name"])
                    $("#roleCode").val(data.data[listName + "Code"])
                    $("#moreDesc").val(data.data.remark)
                    if ($("#menuLevel")) {
                        $("#menuLevel").val(data.data.menuLevel)
                    }
                    if (listName == "user") { //用户渲染组织
                        $("#loginName").val(data.data.userId)
                        $("#loginName").attr("disabled", true)
                        $("#password").val(data.data.password)
                        $("#tel").val(data.data.tel)
                        $("#mail").val(data.data.mail)

                        //渲染单选框数据
                        var orgId = data.data.orgId;
                        getSingleData(listName, orgId)
                            //渲染角色多选数据
                        var roleIds = data.data.roleIds
                        getRole(roleIds, "role")
                    } else if (listName == "role") {
                        var roleIds = data.data.menuIds
                        getRole(roleIds, "menu")
                    } else if (listName == "org") { //用户渲染组织
                        $("#level").val(data.data.orgLevel)
                        var orgId = data.data.parentOrgId;

                        getSingleData(listName, orgId)
                    } else if (listName == "menu") { //用户渲染组织
                        $("#menuLevel").val(data.data.menuLevel)
                        $("#sort").val(data.data.sort)
                        $("#menuPath").val(data.data.menuPath)

                        var orgId = data.data.parentMenuId;
                        getSingleData(listName, orgId)
                        var roleIds = data.data.channelIds;
                        //默认选择系统通道
                        getRole(roleIds, "channel")
                    }
                }

            },
            error: function(e) {

                if (e.status == 500) {
                    layer.msg("系统错误");
                    return
                } else if (e.responseText) {
                    var errorMessage = JSON.parse(e.responseText).errors[0].message;
                    layer.msg(errorMessage);
                }
            }
        })
        $("#buttonBack").show()
        $("#buttonAdd").hide()
        $("#buttonModify").hide()
        $("#buttonDelete").hide()
        $("#refreshData").hide()
        $(".buttonSearchBox").hide()
        $(".bootstrap-table").hide()
        $(".contentInput").show()
        $(".contentInput input").attr("disabled", false)
        $(".contentInput select").attr("disabled", false)
        $(".contentInput textarea").attr("disabled", false)
        $("#submitButton").show()
        $("#saveButton").show()
    } else {
        layer.msg('请选择一项修改');
    }

}
//增加
function add(type) {
    defaultParams = ""
    $("#name").focus()
    $("#buttonBack").show()
    $("#buttonAdd").hide()
    $("#buttonModify").hide()
    $("#buttonDelete").hide()
    $("#refreshData").hide()
    $(".buttonSearchBox").hide()
    $(".bootstrap-table").hide()
    $(".contentInput").show()
    $(".contentInput input").attr("disabled", false)
    $(".contentInput select").attr("disabled", false)
    $(".contentInput textarea").attr("disabled", false)
    $("#submitButton").show()
    $("#saveButton").show()
    $("#name").val("")
    $("#moreDesc").val("")
    if (type == "user") {
        $("#tel").val("")
        $("#mail").val("")
        $("#loginName").val("")
        $("#password").val("")
        $("#loginName").attr("disabled", false)

        // 默认机构信息为选中第一条
        $(".searchable-select-items .searchable-select-item").eq(0).addClass("selected").siblings().removeClass("selected")
        $(".searchable-select-holder").text($(".searchable-select-items .searchable-select-item").eq(0).text())
        $(".mySelect-option div").removeClass('selected')
        getSingleData(type, "")
            // 获取角色信息
        getRole([], "role")
    } else if (type == "role") {
        getRole([], "menu")
    } else if (type == "menu") {
        $("#menuLevel").val("1")
        $(".searchable-select-items .searchable-select-item").eq(0).addClass("selected").siblings().removeClass("selected")
        $(".searchable-select-holder").text($(".searchable-select-items .searchable-select-item").eq(0).text())
        $(".mySelect-option div").removeClass('selected')
        $("#sort").val("1")
        $("#menuPath").val("")
        getRole([], "channel")
        getSingleData(type, "")
    } else if (type == "org") {
        getSingleData(type, "")
        $("#level").val("1")
    }


}

//enter搜索
function noNumbers(e) {
    var keynum;
    var keychar;

    keynum = window.event ? e.keyCode : e.which;
    if (keynum == "13") {
        search()
    }
}
// 搜索
function search() {

    defaultParams = ""
    $("#table").bootstrapTable('destroy');
    tableData.initData()
}

//删除搜索关键字
function removeSearchVal() {
    $("#searchVal").val("")
    $("#searchVal").focus()
}

//提交    $(".searchable-select-item.selected").attr("data-value")
function submitButtonEvent(listName) {
    switch (listName) {
        case "role":
            var arrIds = []
            if ($(".inputWrap ul li i")) {
                var idList = $(".inputWrap ul li i")
                for (var i = 0; i < idList.length; i++) {
                    arrIds.push(idList.eq(i).attr("data-value"))
                }
            }
            var params = {
                "roleName": $("#name").val(),
                "roleCode":$('#roleCode').val(),
                "remark": $("#moreDesc").val(),
                "menuIds": arrIds
            }
            break;


        case "menu":
            var arrIds = []
            if ($(".inputWrap ul li i")) {
                var idList = $(".inputWrap ul li i")
                for (var i = 0; i < idList.length; i++) {
                    arrIds.push(idList.eq(i).attr("data-value"))
                }
            }
            var params = {
                "menuName": $("#name").val(),
                "remark": $("#moreDesc").val(),
                "menuLevel": $("#menuLevel").val(),
                "parentMenuId": $(".searchable-select-item.selected").attr("data-value"),
                "menuPath": $("#menuPath").val(),
                "sort": $("#sort").val(),
                "channelIds": arrIds

            }
            break;
        case "org":
            var params = {
                "orgName": $("#name").val(),
                "remark": $("#moreDesc").val(),
                "orgLevel": $("#level").val(),
                "parentOrgId": $(".searchable-select-item.selected").attr("data-value")
            }
            break;
        case "user":

            var reg = new RegExp("^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$"); //正则表达式

            if ($("#mail").val() && !reg.test($("#mail").val())) {
                layer.msg('请输入正确的邮箱地址');
                return false
            }
            var arrIds = []
            if ($(".inputWrap ul li i")) {
                var idList = $(".inputWrap ul li i")
                for (var i = 0; i < idList.length; i++) {
                    arrIds.push(idList.eq(i).attr("data-value"))
                }
            }
            var params = {
                "userName": $("#name").val(),
                "userId": $("#loginName").val(),
                "password": $("#password").val(),
                "remark": $("#moreDesc").val(),
                "orgId": $(".searchable-select-item.selected").attr("data-value"),
                "tel": $("#tel").val(),
                "mail": $("#mail").val(),
                "roleIds": arrIds
            }
            break;
    }
    $table = $('#table')
    if (defaultParams[listName + "Id"]) { //修改

        $.ajax({
            type: "POST",
            contentType: 'application/json',
            url: "/operation/system/" + listName + "/" + defaultParams[listName + "Id"],
            data: JSON.stringify(params),
            dataType: "json",
            cache: false,
            success: function(data) {
                layer.msg('修改成功', { time: 1000, icon: 1 });
                $("#submitButton").attr("disabled", true)
                $("#table").bootstrapTable('refresh');
                back()
            },
            error: function(e) {
                var errorMessage = JSON.parse(e.responseText).errors[0].message;
                layer.msg(errorMessage);
            }
        })
    } else { //新增
        $.ajax({
                type: "post",
                url: "/operation/system/" + listName + "/",
                contentType: 'application/json',
                data: JSON.stringify(params),
                dataType: "json",
                cache: false,
                success: function(data) {
                    layer.msg('提交成功', { time: 1000, icon: 1 });
                    $("#submitButton").attr("disabled", true)
                    $("#table").bootstrapTable('refresh');
                    back()
                },
                error: function(e) {
                    if (e.responseText) {
                        var errorMessage = JSON.parse(e.responseText).errors[0].message;
                        layer.msg(errorMessage);
                    }

                }
            })
            //
    }
    return false
}

// 获取机构
// function getOrg(type) {
//     // $("#belongPart").html("")
//     if (type) {
//         var url = "/operation/system/menu/"
//     } else {
//         var url = "/operation/system/org/"
//     }

//     $.ajax({
//         url: url,
//         type: "get",
//         dataType: "json",
//         cache: false,
//         success: function(data) {
//             if (data.message === "成功") {
//                 var dataList = data.data.list
//                 var str =' <option value="">无</option>'
//                 if (type == "menu") {
//                     for (var i = 0; i < dataList.length; i++) {
//                         str += ' <option value="' + dataList[i].menuId + '">' + dataList[i].menuName + '</option>'
//                     }
//                 } else {
//                     for (var i = 0; i < dataList.length; i++) {
//                         str += ' <option value="' + dataList[i].orgId + '">' + dataList[i].orgName + '</option>'
//                     }
//                 }

//                 $("#belongPart").html(str)
//                 $('#belongPart').searchableSelect();
//             }

//         },
//         error: function(e) {

//             if (e.status == 500) {
//                 layer.msg("系统错误");
//                 return
//             } else if (e.responseText) {
//                 var errorMessage = JSON.parse(e.responseText).errors[0].message;
//                 layer.msg(errorMessage);
//             }
//         }
//     })
// }

// 渲染单选框数据
function getSingleData(listName, id) {


    if (listName == "menu") {
        var url = "/operation/system/menu/"
    } else {
        var url = "/operation/system/org/"
    }

    $.ajax({
            url: url,
            type: "get",
            dataType: "json",
            cache: false,
            success: function(data) {
                if (data.message === "成功") {
                    var dataList = data.data.list
                    var str = ' <option value="">无</option>'
                    if (listName == "menu") {
                        for (var i = 0; i < dataList.length; i++) {
                            str += ' <option value="' + dataList[i].menuId + '">' + dataList[i].menuName + '</option>'
                        }
                    } else {
                        for (var i = 0; i < dataList.length; i++) {
                            str += ' <option value="' + dataList[i].orgId + '">' + dataList[i].orgName + '</option>'
                        }
                    }

                    $("#belongPart").html(str)
                    $("#belongPart").val(id); //设置值
                    $("#belongPart").searchableSelect(); //
                    $(".searchable-select").eq(1).remove() //清除多余
                        // 
                }

            },
            error: function(e) {

                if (e.status == 500) {
                    layer.msg("系统错误");
                    return
                } else if (e.responseText) {
                    var errorMessage = JSON.parse(e.responseText).errors[0].message;
                    layer.msg(errorMessage);
                }
            }
        })
        // $(".searchable-select").eq(1).remove()
        // var selectList = $(".searchable-select-items .searchable-select-item")
        // for (var i = 0; i < selectList.length; i++) {
        //     if (selectList.eq(i).attr("data-value") === id) {
        //         selectList.eq(i).addClass("selected").siblings().removeClass("selected")
        //         $(".searchable-select-holder").text(selectList.eq(i).text())
        //     }
        // }
}

// 获取角色
function getRole(ids, type) {
    $("#mySelect").html("")
    var url;
    if (type == "channel") {
        url = "/operation/channel/"
    } else {
        url = "/operation/system/" + type + "/"
    }
    $.ajax({
        url: url,
        type: "get",
        dataType: "json",
        cache: false,
        success: function(data) {
            if (data.message === "成功") {
                /**/
                var option = []
                var dataList = data.data.list
                for (var i = 0; i < dataList.length; i++) {
                    option[i] = { "label": dataList[i][type + "Name"], "value": dataList[i][type + "Id"] }

                }
                var mySelect = $("#mySelect").mySelect({
                    mult: true, //true为多选,false为单选
                    option: option,
                    onChange: function(res) { //选择框值变化返回结果
                    }
                });
                mySelect.setResult(ids); //默认选中
            }

        },
        error: function(e) {

            if (e.status == 500) {
                layer.msg("系统错误");
                return
            } else if (e.responseText) {
                var errorMessage = JSON.parse(e.responseText).errors[0].message;
                layer.msg(errorMessage);
            }
        }
    })
}
